# -*- coding: utf-8 -*-
from typing import Any

from sqlalchemy import Select
from sqlmodel import SQLModel, Field, Session, select, insert, update, delete

from settings import engine, auto_session


class Permission(SQLModel, table = True):
    __tablename__ = "permission"
    id:int = Field(primary_key = True, default = None)
    name:str = Field(unique=True)
    privilegelevel:int = Field(default = 0)

    def to_dict(self):
        return {"id": self.id, "name": self.name, "privilegelevel": self.privilegelevel}
@auto_session
def search_permissionid_by_name(name: str, session: Session = None) -> int|None:
    """
    根据权限名搜索权限id
    搜索到则输出id，否则输出-1，错误则输出None
    """
    statement:Select = select(Permission.id).where(Permission.name == name)
    result = session.exec(statement).first()
    if result:
        return result
    else:
        return -1

@auto_session
def search_privilegelevel_by_name(name: str, session: Session = None) -> int | None:
    """
    根据权限名搜索权限权限等级
    搜索到则输出最小权限等级，否则输出-1，错误则输出None
    """
    statement:Select = select(Permission.privilegelevel).where(Permission.name == name)
    result = session.exec(statement).first()
    if result is not None:
        return result
    else:
        return -1

@auto_session
def search_privilegelevel_by_id(id: int, session: Session = None) -> int | None:
    """
    根据权限名搜索权限权限等级
    搜索到则输出最小权限等级，否则输出-1，错误则输出None
    """
    statement:Select = select(Permission.privilegelevel).where(Permission.id == id)
    result = session.exec(statement).first()
    if result is not None:
        return result
    else:
        return -1

@auto_session
def insert_permissions(permissions: list[Permission], session: Session = None) -> int|None:
    """
    插入权限
    插入成功则输出插入数，已存在的权限不在插入数中，但会更新成插入的权限，插入失败输出-1，错误则输出None
    """
    if not permissions:
        return 0
    try:
        count = 0
        ishavenames = []
        for p in permissions:
            chaxunjieguo = search_permissionid_by_name(name=p.name, session=session)
            if chaxunjieguo is not None:
                if chaxunjieguo > 0:
                    ishavenames.append(p.name)

        updates = [p for p in permissions if p.name in ishavenames]
        inserts = [p for p in permissions if p.name not in ishavenames]

        if inserts:
            session.bulk_save_objects(inserts)
            count += len(inserts)

        if updates:
            for p in updates:
                statement:Select = select(Permission).where(Permission.name == p.name)
                result = session.exec(statement).one()
                result.privilegelevel = p.privilegelevel
                # count += 1

        session.flush()
        return count

    except Exception as e:
        session.rollback()
        print(f"操作失败: {str(e)}")
        return -1

@auto_session
def delete_permissions_by_name(names: list[str], session: Session = None) -> int | None:
    """
    批量删除权限
    删除成功则输出删除数量，权限不存在的不计数，删除失败输出-1，错误则输出None
    """
    if not names:
        return 0

    try:
        # 查询存在的权限名称
        statement:Select = select(Permission.name).where(Permission.name.in_(names))
        existing_names = set(session.exec(statement).all())
        
        if not existing_names:
            return 0
            
        # 获取要删除的权限ID列表
        id_stmt = select(Permission.id).where(Permission.name.in_(existing_names))
        permission_ids = session.exec(id_stmt).all()

        # # 先删除关联的UserPermission记录
        # session.exec(delete(UserPermission).where(
        #     UserPermission.permission_id.in_(permission_ids)
        # ))
        
        # 批量删除权限记录
        delete_stmt = delete(Permission).where(
            Permission.id.in_(permission_ids)
        )
        result = session.exec(delete_stmt)
        session.flush()
        
        return result.rowcount
        
    except Exception as e:
        print(e)
        session.rollback()
        return -1


@auto_session
def get_all_privilege(session: Session = None) -> list[dict[str,Any]] | None:
    """
    获取所有权限。

    """
    statement: Select = (select(Permission))
    result: list[Permission] = session.exec(statement).all()
    ret = [p.to_dict() for p in result]
    return ret

@auto_session
def get_all_privilege_not_greater_than_level(level: int, session: Session = None)-> list[dict[str,Any]] | None:
    """
    获取不大于权限等级的权限。
    """
    statement: Select = (select(Permission).where(Permission.privilegelevel <= level))
    result: list[Permission] = session.exec(statement).all()
    ret = [p.to_dict() for p in result]
    return ret

# SQLModel.metadata.create_all(engine)
print(f'共加入{insert_permissions([
    Permission(name = '插入名片'),
    Permission(name = '修改名片'),
    Permission(name = '删除名片'), 
    Permission(name = '查询名片'),
    Permission(name = '插入名片夹'),
    Permission(name = '修改名片夹'),
    Permission(name = '删除名片夹'), 
    Permission(name = '查询名片夹'),
    Permission(name = '管理员新增用户', privilegelevel = 1),
    Permission(name = '管理员重置用户密码', privilegelevel = 1),
    Permission(name = '管理员设置用户权限', privilegelevel = 1), 
    Permission(name = '管理员查询用户信息', privilegelevel = 1),
    Permission(name = '超级管理员设置用户权限等级', privilegelevel = 2)])}条权限')